package com.wl.spring.mvc.web;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConvertor implements Converter<String, Date> {
    SimpleDateFormat yyyymmdd1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat yyyymmdd2 = new SimpleDateFormat("yyyy年MM月dd日");
    SimpleDateFormat yyyymmddhhmmss = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
    @Override
    public Date convert(String source) {
        if(source == null || source.isBlank()) return null;
        source = source.trim(); //去掉空格
        //这是用长度判断，但是最好用正则表达式判断
        if(source.length() == "yyyy-MM-dd".length()) {
            return parse(yyyymmdd1 ,source);
        } else if (source.length() == "yyyy年MM月dd日".length()) {
            return parse(yyyymmdd2,source);
        } else if (source.length() == "yyyy-MM-dd hh:mm:ss".length()) {
            return parse(yyyymmddhhmmss,source);
        }
        return null;
    }

    private Date parse(SimpleDateFormat fmt,String source) {
        try {
            return  fmt.parse(source);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

